package com.microservices.yucloud.appweb.config;

import com.google.common.collect.Maps;
import com.microservices.yucloud.appweb.contants.BizOrderErrorCode;
import com.microservices.yucloud.appweb.enums.BizOrderEventsEnum;
import com.microservices.yucloud.appweb.enums.BizOrderStatusEnum;
import com.microservices.yucloud.appweb.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.statemachine.StateMachine;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zy
 * @date 2019-08-30 14:53
 **/
@Slf4j
@Component
public class BizOrderStateMachineBuildFactory implements InitializingBean {

    @Autowired
    private List<BizOrderStateMachineBuilder> builders;

    @Autowired
    private BeanFactory beanFactory;

    /**
     * 用来存储builder-name及builder的map
     */
    private Map<String, BizOrderStateMachineBuilder> builderMap = Maps.newConcurrentMap();

    /**
     * 创建stateMachine
     */
    StateMachine<BizOrderStatusEnum, BizOrderEventsEnum> createStateMachine(String builderName) {

        BizOrderStateMachineBuilder builder = builderMap.get(builderName);

        StateMachine<BizOrderStatusEnum, BizOrderEventsEnum> stateMachine;
        try {
            stateMachine = builder.build(beanFactory);
        } catch (Exception e) {
            log.error("创建状态机异常", e);
            throw new BusinessException(BizOrderErrorCode.ORDER_GENERIC_EXCEPTION, e.getLocalizedMessage());
        }
        log.info("初始化状态机成功[{}]", stateMachine);
        return stateMachine;
    }

    @Override
    public void afterPropertiesSet() {
        builderMap = builders.stream().collect(Collectors.toMap(
                BaseStateMachineBuilder::getName,
                Function.identity()
        ));
    }
}
